package com.yxc.emqxdemo.utils;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * 字符串工具类
 *
 * @author: 杨旭晨
 * @time: 2022/9/15 11:37
 **/
public class StringUtils {
    /**
     * 将list转换为字符串，用拼接符号拼接
     *
     * @author 杨旭晨
     * @date 10:05 2021/5/9
     * @param list: 要转换的字符串列表
     * @param symbol: 拼接符号
     * @return java.lang.String
     **/
    public static String listToString(List<String> list, String symbol) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + symbol);
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将字符串数组转换成字符串
     *
     * @author YXC
     * @date 2022/9/15 12:02
     * @param arr: 要转换的数组
     * @param symbol: 连接符
     * @return java.lang.String
    **/
    public static String arrayToString(String[] arr, String symbol) {
        StringBuilder sb = new StringBuilder();
        if (arr != null && arr.length != 0) {
            for (int i = 0; i < arr.length; i++) {
                if (i < arr.length - 1) {
                    sb.append(arr[i] + symbol);
                } else {
                    sb.append(arr[i]);
                }
            }
        }
        return sb.toString();
    }

    /**
     * 集合转换成字符串
     *
     * @author YXC
     * @date 2022/10/26 11:01
     * @param list: 集合
     * @param symbol: 分隔符
     * @return java.lang.String
     **/
    public static String collectionToString(Collection<String> list, String symbol) {
        StringBuilder sb = new StringBuilder();
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String str = iterator.next();
            if (iterator.hasNext()) {
                sb.append(str).append(symbol);
            } else {
                sb.append(str);
            }
        }
        return sb.toString();
    }
}
